package com.mlong.admin.modular.unicomjs.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.kordar.admin.kernel.wrapper.BatchDeleteWrapperEntity;
import com.kordar.admin.kernel.wrapper.UpdateWrapperEntity;
import com.kordar.datalist.DatalistService;
import com.kordar.datalist.ResultEntity;
import com.mlong.admin.modular.unicomjs.entity.GoodsType;
import com.mlong.admin.modular.unicomjs.service.GoodsTypeService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

@AllArgsConstructor
@Controller
@RequestMapping("unicomjs")
public class GoodsTypeController {

    private final GoodsTypeService goodsTypeService;
    private final DatalistService datalistService;

    @GetMapping("goods-type/index")
    public String index(Model model) {
        model.addAttribute("data", datalistService.render(goodsTypeService.list(), GoodsType.class));
        return "pages/modular/unicomjs/goods-type/index";
    }

    @GetMapping("goods-type/form")
    public String form(Model model, @RequestParam(required = false, defaultValue = "0") Long id) {
        if (id.equals(0L)) {
            model.addAttribute("header", "新建分类");
            model.addAttribute("model", new GoodsType());
        } else {
            model.addAttribute("header", "修改分类");
            model.addAttribute("isUpdate", true);
            model.addAttribute("model", goodsTypeService.getById(id));
        }

        return "pages/modular/unicomjs/goods-type/form";
    }

    @PostMapping("goods-type/save")
    @ResponseBody
    public ResultEntity<Object> save(@Validated GoodsType goodsType) {
        if (goodsType.getId() == 0) {
            goodsType.setId(null);
            goodsTypeService.save(goodsType);
        } else {
            goodsTypeService.updateById(goodsType);
        }
        return ResultEntity.success();
    }

    @RequestMapping("goods-type/edit")
    @ResponseBody
    public ResultEntity<Object> edit(@RequestBody UpdateWrapperEntity<GoodsType> entity) {
        UpdateWrapper<GoodsType> query = entity.where(GoodsType.class).data().getQuery();
        goodsTypeService.update(query);
        return ResultEntity.success();
    }

    @PostMapping("goods-type/delete")
    @ResponseBody
    public ResultEntity<Object> del(Long id) {
        goodsTypeService.removeById(id);
        return ResultEntity.success();
    }

    @RequestMapping("goods-type/batch-delete")
    @ResponseBody
    public ResultEntity<Object> del(@RequestBody BatchDeleteWrapperEntity<Long> entity) {
        Set<Long> ids = entity.getIds();
        goodsTypeService.removeByIds(ids);
        return ResultEntity.success();
    }

}
